/* eslint-disable consistent-return */
const { verifyToken } = require('../services/auth.service');
const { AppError } = require('../utils/error');
const User = require('../models/user.model');

/**
 * 认证中间件 - 验证用户是否已登录
 */
exports.authenticate = async (req, res, next) => {
  try {
    // 从请求头中获取令牌
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return next(new AppError('未提供认证令牌', 401));
    }

    // 提取令牌
    const token = authHeader.split(' ')[1];
    if (!token) {
      return next(new AppError('无效的认证令牌格式', 401));
    }

    // 验证令牌
    const decoded = verifyToken(token);

    // 检查用户是否存在
    const user = await User.findById(decoded.id);
    if (!user) {
      return next(new AppError('令牌对应的用户不存在', 401));
    }

    // 将用户信息添加到请求对象
    req.user = user;
    next();
  } catch (error) {
    next(new AppError('认证失败', 401));
  }
};

/**
 * 授权中间件 - 检查用户是否有特定角色
 * @param {string[]} roles - 允许访问的角色数组
 */
exports.authorize = (roles = []) => (req, res, next) => {
  if (!req.user) {
    return next(new AppError('需要先进行认证', 401));
  }

  if (roles.length && !roles.includes(req.user.role)) {
    return next(new AppError('没有权限执行此操作', 403));
  }

  next();
};
